import torch.nn as nn


# Convolutional neural network (two convolutional layers)，继承自nn.Module类
class ConvNet(nn.Module):
    def __init__(self, num_classes=10):
        super(ConvNet, self).__init__()
        # nn.Sequential一个有序的容器，神经网络模块将按照在传入构造器的顺序依次被添加到计算图中执行
        self.layer1 = nn.Sequential(
            # 输入通道数，输出通道数，卷积核大小，步长，填充
            nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
            # 将输出的特征图归一化
            nn.BatchNorm2d(16),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        self.layer2 = nn.Sequential(
            nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.MaxPool2d(kernel_size=2, stride=2))
        # 全连接层
        self.fc = nn.Linear(7 * 7 * 32, num_classes)

    def forward(self, x):
        out = self.layer1(x)
        out = self.layer2(out)
        # 将此时的输出重塑进行全连接
        out = out.reshape(out.size(0), -1)
        out = self.fc(out)
        return out

